// usb_wmDlg.cpp : implementation file
//

#include "stdafx.h"
#include "usb_wm.h"
#include "usb_wmDlg.h"
#include  "NetUSB.h"
#include "dbt.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

HWND hwnd=NULL;
static void  TheCallbackFunc(unsigned char* buf, size_t n)
{	
	SendMessage(hwnd,RCV_MSG,(WPARAM)buf,(LPARAM)(n) );
}


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// Cusb_wmDlg dialog




Cusb_wmDlg::Cusb_wmDlg(CWnd* pParent /*=NULL*/)
	: CDialog(Cusb_wmDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void Cusb_wmDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST_MSG, m_wmMsgs);

	DDX_Text(pDX, IDC_EDIT_RXADDR, m_rxad);
	DDX_Text(pDX, IDC_EDIT_TXADDR, m_txad);
	DDX_Text(pDX, IDC_EDIT_BAUD, m_baud);
	DDX_Text(pDX, IDC_EDIT_MAXNO, m_RexMax);
	DDX_Text(pDX, IDC_EDIT_REGSLICE, m_RegSlice);
	DDX_Text(pDX, IDC_EDIT_DATASLICE, m_DataSlice);
	DDX_Text(pDX, IDC_EDIT_DATATMO, m_DataTmo);
	DDX_Text(pDX, IDC_EDIT_RETRYNO, m_RetryMax);
	DDX_Text(pDX, IDC_EDIT_HSLICE, m_ClientSlice[0]);
	DDX_Text(pDX, IDC_EDIT_MSLICE, m_ClientSlice[1]);
	DDX_Text(pDX, IDC_EDIT_LSLICE, m_ClientSlice[2]);
	DDX_Text(pDX, IDC_EDIT_HNO, m_ClientNum[0]);
	DDX_Text(pDX, IDC_EDIT_MNO, m_ClientNum[1]);
	DDX_Text(pDX, IDC_EDIT_LNO, m_ClientNum[2]);
	DDX_Text(pDX, IDC_EDIT_SOFTADDR, m_serid);
	DDX_Text(pDX, IDC_EDIT_DID, m_did);
	DDX_Text(pDX, IDC_EDIT_SID, m_sid);
	DDX_Text(pDX, IDC_EDIT_DATA, m_data);
	DDX_Text(pDX, IDC_EDIT_IDLE, m_idle);
	DDX_Text(pDX, IDC_EDIT_USBSTATUS, m_usbstatus);

}

BEGIN_MESSAGE_MAP(Cusb_wmDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_TIMER()
	ON_MESSAGE(WM_UPDATEDATA, OnUpdateData)
	ON_WM_DEVICECHANGE()
	ON_WM_CLOSE()	
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDOK, &Cusb_wmDlg::OnBnClickedOk)
	ON_BN_CLICKED(IDC_BTN_CLR, &Cusb_wmDlg::OnBnClickedBtnClr)
	ON_BN_CLICKED(IDC_BTN_START, &Cusb_wmDlg::OnBnClickedBtnStart)
	ON_BN_CLICKED(IDC_BTN_PASUE, &Cusb_wmDlg::OnBnClickedBtnPasue)
	ON_BN_CLICKED(IDC_BTN_REG, &Cusb_wmDlg::OnBnClickedBtnReg)
	ON_BN_CLICKED(IDC_BTN_ACK, &Cusb_wmDlg::OnBnClickedBtnAck)
	ON_BN_CLICKED(IDC_BTN_DATA, &Cusb_wmDlg::OnBnClickedBtnSubData)
	ON_BN_CLICKED(IDC_BTN_LAST, &Cusb_wmDlg::OnBnClickedBtnLast)
	ON_BN_CLICKED(IDC_BTN_LOGOUT, &Cusb_wmDlg::OnBnClickedBtnLogout)
	ON_BN_CLICKED(IDC_BTN_SETPARA, &Cusb_wmDlg::OnBnClickedBtnSetpara)
	ON_BN_CLICKED(IDC_BTN_CLRDATA, &Cusb_wmDlg::OnBnClickedBtnClrdata)
END_MESSAGE_MAP()


// Cusb_wmDlg message handlers

BOOL Cusb_wmDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here
	NetusbStopListen();
	NetusbRegisterNotification(GetSafeHwnd());

	m_rxad=1234;
	m_txad=5678;
	m_baud=106;
	m_serid=4;
	m_RexMax=30;
	m_RegSlice=3000;
	m_DataSlice=2000;
	m_DataTmo=16000;
	m_RetryMax=3;
	m_ClientSlice[0]=2000;
	m_ClientSlice[1]=2000;
	m_ClientSlice[2]=2000;

	m_ClientNum[0]=0;
	m_ClientNum[1]=0;
	m_ClientNum[2]=0;

	m_serid=1;
	m_did=1;
	m_sid=5;
	m_idle=10*1000;	/*10 min*/
	
	UpdateData(false);
	hwnd=GetSafeHwnd();
	m_hwnd=hwnd;

	m_tmo=true;
	m_pWmDrv = new CWmDrv(m_rxad, m_txad, m_baud, m_serid,this, 
					m_RexMax, m_ClientNum, m_ClientSlice, m_DataTmo,
					m_RegSlice, m_DataSlice,  m_RetryMax, m_idle);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void Cusb_wmDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void Cusb_wmDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR Cusb_wmDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void Cusb_wmDlg::OnBnClickedOk()
{
	// TODO: Add your control notification handler code here

	char buffer[10];
	buffer[9]=0;
	m_wmMsgs.InsertString(0, _T("xxx"));

	OnOK();
}

void Cusb_wmDlg::OnTimer(UINT   nIDEvent)
{
	m_tmo=true;
	CDialog::OnTimer(nIDEvent);
}
void Cusb_wmDlg::OnBnClickedBtnClr()
{
	// TODO: Add your control notification handler code here
	m_pWmDrv->StopUSBwm();
	m_wmMsgs.ResetContent();
}

void Cusb_wmDlg::OnBnClickedBtnStart()
{
	// TODO: Add your control notification handler code here
	m_pWmDrv->StartUSBwm();
	m_wmMsgs.InsertString(0, _T("StartUSBwm"));


}

void Cusb_wmDlg::OnBnClickedBtnPasue()
{
	// TODO: Add your control notification handler code here
	m_pWmDrv->PauseUSBwm();
	CString str("resume");
	GetDlgItem(IDC_BTN_PASUE)->GetWindowText(str);
	UpdateData(false);
}

void Cusb_wmDlg::OnBnClickedBtnReg()
{
	// TODO: Add your control notification handler code here
	frame aaa;

	 UpdateData(true);
	aaa.cmd=CMD_TYPE(NTC, REG_REQ);
	aaa.did=(u16)m_did;
	aaa.sid=(u16)m_sid;
	m_pWmDrv->OnReceiveUSBMSG((WPARAM)&aaa,(LPARAM)(sizeof(aaa)));	
}

void Cusb_wmDlg::OnBnClickedBtnAck()
{
	// TODO: Add your control notification handler code here
	frame aaa;
	 UpdateData(true);
	aaa.cmd=CMD_TYPE(RSP, CHK_REP);
	aaa.did=(u16)m_did;
	aaa.sid=(u16)m_sid;
	m_pWmDrv->OnReceiveUSBMSG((WPARAM)&aaa,(LPARAM)(sizeof(aaa)));	

}

void Cusb_wmDlg::OnBnClickedBtnSubData()
{
	// TODO: Add your control notification handler code here

	frame aaa;
	 UpdateData(true);
	aaa.cmd=CMD_TYPE(RSP, DATA_REP);
	aaa.did=(u16)m_did;
	aaa.sid=(u16)m_sid;
	m_pWmDrv->OnReceiveUSBMSG((WPARAM)&aaa,(LPARAM)(sizeof(aaa)));	

}


void Cusb_wmDlg::OnBnClickedBtnLast()
{
	// TODO: Add your control notification handler code here
	frame aaa;
	 UpdateData(true);
	aaa.cmd=CMD_TYPE(RSP, DATA_FNL);
	aaa.did=(u16)m_did;
	aaa.sid=(u16)m_sid;
	m_pWmDrv->OnReceiveUSBMSG((WPARAM)&aaa,(LPARAM)(sizeof(aaa)));	

}

void Cusb_wmDlg::OnBnClickedBtnLogout()
{
	// TODO: Add your control notification handler code here
	frame aaa;
	 UpdateData(true);
	aaa.cmd=CMD_TYPE(NTC, REG_CNL);
	aaa.did=(u16)m_did;
	aaa.sid=(u16)m_sid;
	m_pWmDrv->OnReceiveUSBMSG((WPARAM)&aaa,(LPARAM)(sizeof(aaa)));	

}

void Cusb_wmDlg::OnBnClickedBtnSetpara()
{
	// TODO: Add your control notification handler code here
	

}

void Cusb_wmDlg::SetWMTimer(u32 tmo)
{
	m_tmo=false;
	SetTimer(1,tmo,NULL);
}
void Cusb_wmDlg::KillWMTimer()
{
	KillTimer(1);
}

bool Cusb_wmDlg::ChkWMTimer()
{
	return m_tmo;
}

void Cusb_wmDlg::FreshItemNum()
{
	m_ClientNum[0]=m_pWmDrv->m_ClientNum[0];
	m_ClientNum[1]=m_pWmDrv->m_ClientNum[1];
	m_ClientNum[2]=m_pWmDrv->m_ClientNum[2];
}

void Cusb_wmDlg::FreshMsgList(char * str0)
{
	CString str(str0);
	m_wmMsgs.InsertString(0, str); 
}

LRESULT Cusb_wmDlg::OnUpdateData(WPARAM wParam, LPARAM lParam)
{
	 UpdateData(true);

	if(lParam)
	{
		FreshItemNum();
	}
	else
	{
		FreshMsgList((char *)wParam);
	}

	 UpdateData(false);
	 return 0;
}


void Cusb_wmDlg::OnBnClickedBtnClrdata()
{
	// TODO: Add your control notification handler code here
	m_data="XXX";
	UpdateData(false);
}


BOOL Cusb_wmDlg::OnDeviceChange(UINT nEventType, DWORD dwData)
{
	DWORD results;

	switch(nEventType)
	{
		// A device has been inserted and is now available.
	case DBT_DEVICEARRIVAL:		
		AttemptConnection();
		break;

		// A device has been removed from USB.
	case DBT_DEVICEREMOVECOMPLETE:
		// Check for  devices
		results = NetusbGetNumDevices(VID_NETUSB, PID_NETUSB905);
		if (results == 0)
		{
			// Close device if found
			Sleep(10);
			m_usbstatus="USB Disconnect";
			UpdateData(false);
			m_IsConnected = false;
			NetusbStopListen();
			NetusbClose();
		}
		break;

	default:
		break;
	}

	return TRUE;
}



void Cusb_wmDlg::AttemptConnection(void)
{

	if (m_IsConnected ==true)
	{
		MessageBox(_T("USB has beeb connected"));
		return;
	}
	DWORD results;
	// Check for connected devices
	results = NetusbGetNumDevices(VID_NETUSB, PID_NETUSB905);
	// Only proceed if 1 device is found
	if (results ==1)
	{
		// Open connection to device
		results = NetusbOpen(0,VID_NETUSB, PID_NETUSB905);
		// If device connection not established, output failure
		if (results != HID_DEVICE_SUCCESS)
		{
			MessageBox(_T("Error in connecting to device."));
		}
		else
		{
			m_IsConnected = true;
			m_usbstatus="USB Connect";
			UpdateData(false);
			NetusbSetCallback(TheCallbackFunc);
			NetusbStartListen();
		}
	}
	else
	{
		MessageBox(_T("No device found."));
	}
}

void Cusb_wmDlg::OnClose()
{
	// TODO: Add your message handler code here and/or call default
	NetusbUnregisterNotification();
	NetusbClose();
	CDialog::OnClose();
}

